#!/usr/bin/env python3
"""
Debug script to trace the CLI course display issue
"""

import sys
import os

# 添加项目根目录到Python路径
project_root = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, project_root)

from system.lms_system import LMSSystem
from ui.cli import CLI
from managers.course_manager import CourseManager

def debug_course_loading():
    """Debug the course loading process step by step"""
    
    print("=== Step 1: Initialize LMS System ===")
    lms_system = LMSSystem()
    success = lms_system.initialize()
    print(f"System initialization: {success}")
    
    print(f"\n=== Step 2: Check Course Manager ===")
    print(f"Course manager exists: {lms_system.course_manager is not None}")
    if lms_system.course_manager:
        print(f"Course manager type: {type(lms_system.course_manager)}")
        print(f"Course manager ID: {id(lms_system.course_manager)}")
        print(f"Courses in manager: {len(lms_system.course_manager.courses)}")
        print(f"Courses dict: {list(lms_system.course_manager.courses.keys())}")
    
    print(f"\n=== Step 3: Check get_all_courses() ===")
    if lms_system.course_manager:
        courses = lms_system.course_manager.get_all_courses()
        print(f"get_all_courses() returned: {len(courses)} courses")
        if courses:
            print("First course details:")
            course = courses[0]
            print(f"  ID: {course.get_id()}")
            print(f"  Name: {course.get_name()}")
            print(f"  Current students: {course.get_current_students()}")
    
    print(f"\n=== Step 4: Create CLI and test ===")
    cli = CLI(lms_system)
    print(f"CLI created successfully")
    print(f"CLI system course manager: {cli.system.course_manager is not None}")
    if cli.system.course_manager:
        print(f"CLI course manager ID: {id(cli.system.course_manager)}")
        print(f"CLI courses: {len(cli.system.course_manager.courses)}")
        
        # Test the display_courses method directly
        print(f"\n=== Step 5: Test display_courses method ===")
        try:
            # Manually call the logic from display_courses
            if not cli.system or not cli.system.course_manager:
                print("Course manager unavailable")
            else:
                courses = cli.system.course_manager.get_all_courses()
                print(f"Courses retrieved: {len(courses)}")
                if not courses:
                    print("No courses found")
                else:
                    print("Courses found:")
                    for i, course in enumerate(courses):
                        print(f"  {i+1}. {course.get_name()} ({course.get_id()})")
        except Exception as e:
            print(f"Error in display_courses: {e}")
            import traceback
            traceback.print_exc()

if __name__ == "__main__":
    debug_course_loading()